package main

//go get github.com/yuin/gopher-lua
import (
	"MqttCloudProtocolServer/publiclib/define"
	"MqttCloudProtocolServer/publiclib/logiclib"
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/chai2010/winsvc"
	"github.com/wonderivan/logger"
)

//服务名称：MQTT2TCPWEBServer
//显示名称：MQTT2TCPWeb服务器
//描述：调试与监视ProtocolServer进程的调试信息与报文、运行状态、注册信息
var (
	appPath              string
	flagServiceName      = flag.String("service-name", "MQTT2TCPWEBServer", "Set service name")
	flagServiceDesc      = flag.String("service-desc", "MQTT2TCPWeb服务器", "Set service description")
	flagServiceInstall   = flag.Bool("service-install", false, "Install service")
	flagServiceUninstall = flag.Bool("service-remove", false, "Remove service")
	flagServiceStart     = flag.Bool("service-start", false, "Start service")
	flagServiceStop      = flag.Bool("service-stop", false, "Stop service")
	flagChildProcess     = flag.Bool("child-process", false, "Child Process")
	server               webServer
	isrunning            bool
)

func init() {
	// change to current dir
	var err error
	if appPath, err = winsvc.GetAppPath(); err != nil {
		logger.Fatal(err)
	}
	logger.Info(appPath)
	if err := os.Chdir(filepath.Dir(appPath)); err != nil {
		logger.Fatal(err)
	}
	define.InitInternalPath()
	define.CheckIsLog("web.log")
	isrunning = true
}

//StartServer 启动服务
func StartServer() {
	logger.Info("Web Server Start")
	//go getCMD("WebServer")
	server.Start(define.WebPath)
	//server.Start("web\\CloudManagerWeb")
	isrunning = false
	logger.Info("Web Server Stoped")
}
func getCMD(name string) {
	client := new(logiclib.RPCClientManager)
	client.Init()
	client.Start()
	for isrunning {
		cmd := client.GetCommand(&name)
		if cmd != nil {
			if cmd.Name == name {
				switch strings.ToUpper(cmd.Command) {
				case "STOP":
					StopServer()
					break
				}
			}
		}
		time.Sleep(time.Millisecond * 100)
	}
}

//StopServer 停止服务
func StopServer() {
	server.Stop()
}

func mainwin() {
	flag.Parse()
	/*// install service
	if *flagServiceInstall {
		logger.Info("1")
		if err := winsvc.InstallService(appPath, *flagServiceName, *flagServiceDesc); err != nil {
			log.Fatalf("installService(%s, %s): %v\n", *flagServiceName, *flagServiceDesc, err)
		}
		fmt.Printf("Done\n")
		return
	}
	// remove service
	if *flagServiceUninstall {
		logger.Info("2")
		if err := winsvc.RemoveService(*flagServiceName); err != nil {
			log.Fatalln("removeService:", err)
		}
		fmt.Printf("Done\n")
		return
	}
	// start service
	if *flagServiceStart {
		logger.Info("3")
		if err := winsvc.StartService(*flagServiceName); err != nil {
			log.Fatalln("startService:", err)
		}
		fmt.Printf("Done\n")
		return
	}
	// stop service
	if *flagServiceStop {
		logger.Info("4")
		if err := winsvc.StopService(*flagServiceName); err != nil {
			log.Fatalln("stopService:", err)
		}
		fmt.Printf("Done\n")
		return
	}
	// run as service
	if !winsvc.InServiceMode() {
		logger.Info("5")
		log.Println("main:", "runService")
		if err := winsvc.RunAsService(*flagServiceName, StartServer, StopServer, false); err != nil {
			log.Fatalf("svc.Run: %v\n", err)
		}
		return
	}*/
	// run as normal
	if *flagChildProcess {
		logger.Info("CHILD MODE")
		go getCMD("WebServer")
	} else {
		println("NOT CHILD MODE")
		var cmdLine string
		consoleCmd := func() {
			for isrunning && strings.ToUpper(cmdLine) != "EXIT" {
				//define.WriteCommand(cmdLine)
				fmt.Scanln(&cmdLine)
				time.Sleep(time.Second)
			}
			StopServer()
			//mainContent.MainCmd <- "EXIT"
		}
		go consoleCmd()
	}
	/*processes := make([]*manager.ProcessBase, 0)
	isDaemon := false
	go manager.RPCServerStart(processes, &isDaemon)*/
	StartServer()
	//mainContent.Stop(false)
}
